package com.ruoyi.project.pro;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import java.io.File;
import java.io.IOException;

/**
 * @program: zhizun
 * @author: Mrs.ye
 * @create: 2020-09-18 21:32
 * @description:
 **/
public class COSTest {
    private static final String SecretId = "AKIDPs3SXMm4wYYIn2CyhAPkpJWSs2ydtJq6";
    private static final String SecretKey = "80hV4OIwLTKvMcbMBm9G0TkQs64mGQmt";

    public static void main(String[] args) {
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials("AKIDPs3SXMm4wYYIn2CyhAPkpJWSs2ydtJq6", "80hV4OIwLTKvMcbMBm9G0TkQs64mGQmt");
        // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region("ap-guangzhou");
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);

        // 指定要上传的文件
        File localFile = new File("C:\\Users\\86189\\Desktop\\timg.jpg");
        // 指定要上传到的存储桶
        String bucketName = "tcr-5cb5kifq-1302869269";
        // 指定要上传到 COS 上对象键
        String key = "yim.jpg";
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
       PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

        // Bucket的命名格式为 BucketName-APPID ，此处填写的存储桶名称必须为此格式
        // 方法1 获取下载输入流
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        COSObject cosObject = cosClient.getObject(getObjectRequest);
        COSObjectInputStream cosObjectInput = cosObject.getObjectContent();
        // 下载对象的 CRC64
        String crc64Ecma = cosObject.getObjectMetadata().getCrc64Ecma();

        // 关闭输入流
        try {
            cosObjectInput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 方法2 下载文件到本地
        String outputFilePath = "D:\\exampleobject.jpg";
        File downFile = new File(outputFilePath);
        getObjectRequest = new GetObjectRequest(bucketName, key);
        ObjectMetadata downObjectMeta = cosClient.getObject(getObjectRequest, downFile);
    }
}
